const http = require('http')
const data = require('./data/index.json')
const app = http.createServer((require,response)=>{
    if (require.url === '/') {
        response.setHeader('content-type','text/html;charset=utf-8')
        let str = `<ul>`
        for (let i = 0; i < data.length; i++) {
            str+=`
                <li><a href='/detail?id=${data[i].id}'>${data[i].newsTitle}</a></li>
            `          
        }
        str += `</ul>`
        response.end(str)      
    }

    if (require.url.split('?')[0] === '/detail') {
        response.setHeader('content-type','text/html;charset=utf-8')
        // 获取id
        let id = require.url.split('=')[1];
        // 通过id查找对应对象
        let obj = data.find((item)=>{
            return item.id === id
        })
        let str2 = `
            <h3>${obj.newsTitle}</h3>
            <p>${obj.newsContent}</p>
        `;
        response.end(str2)
    }
})
app.listen(80,()=>{
    console.log('访问成功');
})
